package com.yami.shop.webservice.api.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.UserService;
import com.yami.shop.webservice.common.service.WapiUserService;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;


/**
 *
 * @ClassName:
 * @Description: 用户业务接口
 * @Author:
 * @Date: 2
 * @History 修改描述
 */
@RestController
@RequestMapping( "/wapi/user")
public class UserWSController{
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WapiUserService wapiUserService;
    @Autowired
    private UserService userService;

    /**
     * @param
     * @return 交易所userid(即用户登录交易所得登录账号)
     * @description: 获取交易系统用户编码
     */
    @RequestMapping( "/getWapiUserId")
    @ResponseBody
    public ServerResponseEntity<Map<String,Object>> getWapiUserId() {
        try {
            String userId = SecurityUtils.getUser().getUserId();
            User byUserId = userService.getUserByUserId(userId);
            if(byUserId==null){
                throw new YamiShopBindException("yami.user.account.no.exist");
            }else if(StrUtil.isEmpty(byUserId.getIdNumber())){
                throw new YamiShopBindException("yami.webservice.authentication.isNotempty");
            }
            return  ServerResponseEntity.success(wapiUserService.getWapiUserIdByCardId(byUserId.getIdNumber()));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("异常: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            throw new YamiShopBindException(e.getMessage());
        }
    }


    /**
     * @param  cardId 商城
     * @return 交易所userid(即用户登录交易所得登录账号)
     * @description: 获取交易系统用户编码
     */
    @RequestMapping( "/getWapiUserIdByCardId")
    @ResponseBody
    public ServerResponseEntity<Map<String,Object>> getWapiUserIdByCardId(String cardId) {
        try {
            return  ServerResponseEntity.success(wapiUserService.getWapiUserIdByCardId(cardId));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("异常: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            throw new YamiShopBindException(e.getMessage());
        }
    }

    /**
     *
     *
     * @return 获验证码
     * @description: 获取验证码
     */
    @RequestMapping( "/getLoginImg")
    @ResponseBody
    public ServerResponseEntity<Map<String,Object>> getLoginImg(String token) {
        try {
            return  ServerResponseEntity.success(wapiUserService.getLoginImg(token));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("异常: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            throw new YamiShopBindException(e.getMessage());
        }
    }



    /**
     * @param  userId 交易所用户编码即登录账户
     * @param  pwdCode 用户密码
     * @param  token  商城token
     * @param  checkCode  验证码结果
     * @return
     * @description: 交易系统用户编码登录
     */
    @RequestMapping( "/wapiLogin")
    @ResponseBody
    public ServerResponseEntity<Map<String,Object>> wapiLogin(String userId,String pwdCode,String token,String checkCode,HttpServletRequest request) {
        try {
            return  ServerResponseEntity.success(wapiUserService.wapiLogin(userId,pwdCode,token,checkCode,request));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("异常: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            throw new YamiShopBindException(e.getMessage());
        }
    }

    /**
     * param jsonObject 包含 userAccount 交易所用户编码即登录账户 pwdCode 用户密码 token  商城token checkCode  验证码结果
     * @param
     * @return
     * @description: 交易系统用户编码登录并保持身份证号
     */
    @PostMapping( "/wapiLoginAndSave")
    @ResponseBody
    public ServerResponseEntity<Map<String,Object>> wapiLoginAndSave(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        try {
            String userId = SecurityUtils.getUser().getUserId();
            User byUserId = userService.getUserByUserId(userId);
            if(byUserId==null){
                throw new YamiShopBindException("yami.user.account.no.exist");
            }else if(StrUtil.isEmpty(byUserId.getIdNumber())){
                throw new YamiShopBindException("yami.webservice.authentication.isNotempty");
            }else if(!StrUtil.isEmpty(byUserId.getSettleAccount())){
                throw new YamiShopBindException("yami.webservice.Hengsheng.account.isNotempty");
            }
            String userAccount  = jsonObject.getString("userAccount");
            String pwdCode  = jsonObject.getString("pwdCode");
            String token   = jsonObject.getString("token");
            String checkCode  = jsonObject.getString("checkCode");
            if(StrUtil.isEmpty(pwdCode) || StrUtil.isEmpty(token) || StrUtil.isEmpty(checkCode) || StrUtil.isEmpty(userAccount)){
                throw new YamiShopBindException("yami.sys.illegalArgument");
            }

            return  ServerResponseEntity.success(wapiUserService.wapiLoginAndSave(userId,byUserId.getIdNumber(),userAccount,pwdCode,token,checkCode,request));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("异常: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            throw new YamiShopBindException(e.getMessage());
        }
    }

    /**
     * @param   userId
     * @return
     * @description: 交易系统用户编码获取身份证号和状态
     */
    @RequestMapping( "/getWapiCardIdByUserId")
    @ResponseBody
    public ServerResponseEntity<Map<String,Object>> getWapiCardIdByUserId(String userId) {
        try {
            return  ServerResponseEntity.success(wapiUserService.getWapiCardIdByUserId(userId));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("异常: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            throw new YamiShopBindException(e.getMessage());
        }
    }

    /**
     *
     * @param
     * @return
     * @description: 验证支付密码
     */
    @PostMapping( "/checkPayPosswordByUserIdAndPwd")
    @ResponseBody
    public ServerResponseEntity<Boolean> checkPayPosswordByUserIdAndPwd(@RequestBody JSONObject jsonObject) {
        try {
            String userId  = jsonObject.getString("userId");
            String pwd  = jsonObject.getString("pwd");
            Boolean r = wapiUserService.checkPayPosswordByUserIdAndPwd(userId,pwd);
            return ServerResponseEntity.success(r);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接口异常: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            throw new YamiShopBindException(e.getMessage());
        }
    }

    /**
     *
     * @param
     * @return
     * @description: 验证支付密码
     */
    @RequestMapping( "/getAccout")
    @ResponseBody
    public ServerResponseEntity<String> getAccountByUserIdAndMall(String userId) {
        try {
            String r = wapiUserService.getAccountByUserIdAndMall(userId);
            return ServerResponseEntity.success(r);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接口异常: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            throw new YamiShopBindException(e.getMessage());
        }
    }

    /**
     *
     * @param
     * @return
     * @description: 发短信
     */
    @RequestMapping( "/sendsms")
    @ResponseBody
    public ServerResponseEntity sendsms(String phone) {
        try {
            wapiUserService.sendsms(phone);
            return ServerResponseEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接口异常: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            throw new YamiShopBindException(e.getMessage());
        }
    }

    /**
     *单图
     * @param
     * @return
     * @description: 上传
     */
    @RequestMapping( "/updataImgIng")
    @ResponseBody
    public ServerResponseEntity<String> updataImgIng(@RequestParam("file") MultipartFile file) {
        try {
            if(file==null||file.isEmpty()){
                throw new YamiShopBindException("yami.sys.illegalArgument");
            }
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            String filename = file.getOriginalFilename();
            filename = filename.contains(".")?filename:filename+".png";

            Thumbnails.of(file.getInputStream()).scale(0.8f).outputFormat("jpg").outputQuality(0.5).toOutputStream(os);
            String s = new BASE64Encoder().encodeBuffer(os.toByteArray()).replaceAll("[\\s*\\t\\n\\r]","");
            file.getInputStream().close();
            os.close();
            Map<String, String> map = new HashMap<>();
            map.put("uploadPath",filename);
            map.put("uploadFile", s);
            map.put("uploadSize",String.valueOf(file.getSize()));
            return ServerResponseEntity.success(wapiUserService.updataImg(map));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接口异常: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            throw new YamiShopBindException(e.getMessage());
        }
    }
    /**
     * 多图
     * @param
     * @return
     * @description: 上传
     */
    @RequestMapping( "/updataImgListIng")
    @ResponseBody
    public ServerResponseEntity<String> updataImgListIng(@RequestParam("files") MultipartFile[] files) {
        try {
            if(files==null||files.length==0){
                throw new YamiShopBindException("yami.sys.illegalArgument");
            }
            List<BufferedImage> imgs = new ArrayList<>();
            for (MultipartFile file:files) {
                BufferedImage image = ImageIO.read(file.getInputStream());
                imgs.add(image);
            }
            //合并图片
            BufferedImage newBufferedImage = mergeImage(false,imgs);
            //获取输出流
            ByteArrayOutputStream os2 = new ByteArrayOutputStream();
            ImageIO.write(newBufferedImage, "jpg", os2);
            InputStream is = new ByteArrayInputStream(os2.toByteArray());
            //压缩图片
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            Thumbnails.of(is).scale(0.8f).outputFormat("jpg").outputQuality(0.5).toOutputStream(os);

            String s = new BASE64Encoder().encodeBuffer(os.toByteArray()).replaceAll("[\\s*\\t\\n\\r]","");
            os.close();
            String id = IdUtil.getSnowflake().nextIdStr();
            Map<String, String> map = new HashMap<>();
            map.put("uploadPath",id+".jpg");
            map.put("uploadFile", s);
            map.put("uploadSize",String.valueOf(os.toByteArray().length));
            return ServerResponseEntity.success(wapiUserService.updataImg(map));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接口异常: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            throw new YamiShopBindException(e.getMessage());
        }
    }


    /**
     *
     * @param
     * @return
     * @description: 上传
     */
    @GetMapping( "/updataImgList2")
    @ResponseBody
    public ServerResponseEntity<String> updataImgList2(String files) {
        try {
            if(files==null||files.length() ==0){
                throw new YamiShopBindException("yami.sys.illegalArgument");
            }
            String[] file = files.split(",");
            log.info("上传 文件数量{}",files.length());
            List<BufferedImage> imgs = new ArrayList<>();
            for (String url:file) {
                MultipartFile file1 = urlToMultipartFile(url);
                try{
                    log.info("文件大小名称及是否空，{}，{},{}",file1.getSize(),file1.getName(),file1.isEmpty());
                    BufferedImage image = ImageIO.read(file1.getInputStream());
                    if(Objects.isNull(image)){
                        throw new YamiShopBindException("yami.webservice.Img.error");
                    }
                    imgs.add(image);
                }catch (IOException e){
                    throw new YamiShopBindException("yami.webservice.Img.error");
                }

            }
            //合并图片
            BufferedImage newBufferedImage = mergeImage(false,imgs);
            //获取输出流
            ByteArrayOutputStream os2 = new ByteArrayOutputStream();
            ImageIO.write(newBufferedImage, "jpg", os2);
            InputStream is = new ByteArrayInputStream(os2.toByteArray());
            //压缩图片
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            Thumbnails.of(is).scale(0.8f).outputFormat("jpg").outputQuality(0.5).toOutputStream(os);

            String s = new BASE64Encoder().encodeBuffer(os.toByteArray()).replaceAll("[\\s*\\t\\n\\r]","");
            os.close();
            String id = IdUtil.getSnowflake().nextIdStr();
            Map<String, String> map = new HashMap<>();
            map.put("uploadPath",id+".jpg");
            map.put("uploadFile", s);
            map.put("uploadSize",String.valueOf(os.toByteArray().length));
            return ServerResponseEntity.success(wapiUserService.updataImg(map));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接口异常: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            throw new YamiShopBindException(e.getMessage());
        }
    }



    /**
     * inputStream 转 File
     */
    public static File inputStreamToFile(InputStream ins, String name) throws Exception{
        //System.getProperty("java.io.tmpdir")临时目录+File.separator目录中间的间隔符+文件名
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
//        if (file.exists()) {
//            return file;
//        }
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;
    }

    /**
     * file转multipartFile
     */
    public static MultipartFile fileToMultipartFile(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item=factory.createItem(file.getName(),"text/plain",true,file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }

    /**
     * url转MultipartFile
     */
    public static MultipartFile urlToMultipartFile(String url) throws Exception {
        File file = null;
        MultipartFile multipartFile = null;
        try {
            HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
            httpUrl.connect();
            String id = IdUtil.getSnowflake().nextIdStr();
            file = inputStreamToFile(httpUrl.getInputStream(),id+".png");

            multipartFile = fileToMultipartFile(file);
            httpUrl.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }
    /**
     * 合成任意数量的图片
     *
     * @param isHorizontal
     * @param imgs
     * @return
     * @throws IOException
     */
    public static BufferedImage mergeImage(boolean isHorizontal, List<BufferedImage> imgs) throws IOException {
        // 生成新图片
        BufferedImage DestImage = null;
        // 计算新图片的长和高
        int allw = 0, allh = 0, allwMax = 0, allhMax = 0;
        for (BufferedImage img : imgs) {
            allw += img.getWidth();
            allh += img.getHeight();
            if (img.getWidth() > allwMax) {
                allwMax = img.getWidth();
            }
            if (img.getHeight() > allhMax) {
                allhMax = img.getHeight();
            }
        }
        // 创建新图片
        if (isHorizontal) {
            DestImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);
        } else {
            DestImage = new BufferedImage(allwMax, allh, BufferedImage.TYPE_INT_RGB);
        }

        // 合并所有子图片到新图片
        int wx = 0, wy = 0;
        for (BufferedImage img : imgs) {
            int w1 = img.getWidth();
            int h1 = img.getHeight();
            // 从图片中读取RGB
            int[] ImageArrayOne = new int[w1 * h1];
            ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中
            if (isHorizontal) { // 水平方向合并
                DestImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            } else { // 垂直方向合并
                DestImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            }
            wx += w1;
            wy += h1;
        }
        return DestImage;
    }

    /**
     *
     * @param
     * @return
     * @description: 获取服务商
     */
    @RequestMapping( "/getServiceUser")
    @ResponseBody
    public ServerResponseEntity<String> getServiceUser(String phone) {
        try {
            return ServerResponseEntity.success(wapiUserService.getServiceUser(phone));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接口异常: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            throw new YamiShopBindException(e.getMessage());
        }
    }

    /**
     *
     * @param
     * @return
     * @description: 注册
     */
    @PostMapping("/wapiRegister")
    @ResponseBody
    public ServerResponseEntity wapiRegister(@RequestBody JSONObject jsonObject) {
        try {
            String password = jsonObject.getString("password");
            String account  = jsonObject.getString("account");
            String regChkCode  = jsonObject.getString("regChkCode");
            String cellPhone  = jsonObject.getString("cellPhone");
            String imgAttach2  = jsonObject.getString("imgAttach2");
            String imgAttach7 = jsonObject.getString("imgAttach7");
            String userId = SecurityUtils.getUser().getUserId();
            //根据imgAttach2 上传获取合成图
            ServerResponseEntity<String> stringServerResponseEntity2 = updataImgList2(imgAttach2);
            ServerResponseEntity<String> stringServerResponseEntity7 = updataImgList2(imgAttach7);

            wapiUserService.wapiRegister(password,account,regChkCode,cellPhone,stringServerResponseEntity2.getData().toString(),stringServerResponseEntity7.getData().toString(),userId);
            return ServerResponseEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接口异常: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            throw new YamiShopBindException(e.getMessage());
        }
    }

}
